package com.tekj.cxqcb.view.Module.activity.StoreModule;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.squareup.picasso.Picasso;
import com.tekj.cxqcb.MainBActivity;
import com.tekj.cxqcb.R;
import com.tekj.cxqcb.config.enums.EventBusMsgBean;
import com.tekj.cxqcb.operation.BusinessDao;
import com.tekj.cxqcb.operation.resultBean.ApiShopServiceSelectAllBean;
import com.tekj.cxqcb.operation.resultBean.PubStatusBean;
import com.tekj.cxqcb.operation.resultBean.SelectByIdBean;
import com.tekj.cxqcb.operation.resultBean.SelectByLevelBean;
import com.tekj.cxqcb.view.Module.activity.NotShelfGoodsActivity;
import com.tekj.cxqcb.view.Module.adapter.ScreenAdapter;
import com.tekj.cxqcb.view.Module.adapter.StoreManagementAdapter;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenu;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.touch.OnItemMoveListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collections;

import butterknife.BindView;
import butterknife.OnClick;
import common.base.activity.BaseActivity;
import common.base.operationHelper.Bean.BindingViewBean;
import common.tool.Tools;
import es.dmoral.toasty.Toasty;

/**
 * 门店管理
 */
public class StoreManagementActivity extends BaseActivity {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_l)
    TextView tvL;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_r)
    ImageView ivR;
    @BindView(R.id.tv_r)
    TextView tvR;
    @BindView(R.id.ll_right)
    LinearLayout llRight;
    @BindView(R.id.rl_title_bg)
    RelativeLayout rlTitleBg;
    @BindView(R.id.img_photo)
    ImageView imgPhoto;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_Fraction)
    TextView tvFraction;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_Shop)
    LinearLayout llShop;
    @BindView(R.id.tv_tab1)
    TextView tvTab1;
    @BindView(R.id.tv_type1)
    TextView tvType1;
    @BindView(R.id.tv_type2)
    TextView tvType2;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.ll_tab)
    LinearLayout llTab;
    @BindView(R.id.tv_search_num)
    TextView tvSearchNum;
    @BindView(R.id.ll_search_result)
    LinearLayout llSearchResult;
    @BindView(R.id.appbar)
    AppBarLayout appbar;
    @BindView(R.id.vp_main)
    SwipeRecyclerView vpMain;
    @BindView(R.id.fab_main)
    FloatingActionButton fabMain;
    @BindView(R.id.coordinator)
    CoordinatorLayout coordinator;
    @BindView(R.id.tv_IsBusiness)
    TextView tvIsBusiness;


    private StoreManagementAdapter adapter;

    private ScreenAdapter type1Adapter;

    private ScreenAdapter type2Adapter;

    private BusinessDao businessDao;

    private SelectByIdBean.DataBeanX.DataBean data;

    @Override
    public void init() {
        tvTitle.setText("店铺管理");
        tvR.setText("编辑");
        tvR.setTextColor(getResources().getColor(R.color.colorPrimary));
        EventBus.getDefault().register(this);
        initAdapter();
        businessDao = new BusinessDao(activity, this);
        businessDao.selectAll(MainBActivity.User.getUserId());
        businessDao.selectByLevel(1, "");

    }

    @Override
    public int setLayout() {
        return R.layout.activity_store_management;
    }

    boolean isFirst;

    @Override
    public void initLoadStart() {
        if (isFirst) {
            loading.show();
            isFirst = false;
        } else
            showDialog();
    }

    @Override
    public void initLoadEnd() {
        loading.dismiss();
        dialog.dismiss();
    }

    @Override
    public void initBindingView(Object mBean) {
        BindingViewBean bindingViewBean = (BindingViewBean) mBean;
        switch (bindingViewBean.getmEnumStatus()) {
            case 店铺服务分类:
                SelectByLevelBean selectByIdBean = (SelectByLevelBean) bindingViewBean.getBean();
                if ("0000000".equals(selectByIdBean.getCode())) {
                    type1Adapter.setNewData(selectByIdBean.getData().getList());
                }
                break;
            case 店铺服务分类2:
                SelectByLevelBean selectByIdBean2 = (SelectByLevelBean) bindingViewBean.getBean();
                if ("0000000".equals(selectByIdBean2.getCode())) {
                    tvType2.setVisibility(View.VISIBLE);
                    tvType2.setText("请选择服务组");
                    type2Adapter.setNewData(selectByIdBean2.getData().getList());
                    type2Adapter.setCheckItem(-1);
                }
                break;
            case 通过id查找店铺:
                SelectByIdBean byIdBean = (SelectByIdBean) bindingViewBean.getBean();
                if ("0000000".equals(byIdBean.getCode())) {
                    if (byIdBean.getData().getData() == null) {
                        startActivity(new Intent(activity, AdministrationActivity.class));
                        finish();
                    } else
                        setViewData(byIdBean.getData().getData());
                } else {
                    Toasty.normal(activity, byIdBean.getMsg()).show();
                }
                break;
            case 筛选获取商品列表:
                ApiShopServiceSelectAllBean selectAllBean = (ApiShopServiceSelectAllBean) bindingViewBean.getBean();
                if ("0000000".equals(selectAllBean.getCode())) {
                    adapter.setNewData(selectAllBean.getData().getList());
                    tvSearchNum.setText("共查询到" + selectAllBean.getData().getAllDownNum() + "条未上架的商品记录");
                    llSearchResult.setVisibility(adapter.getData().size() > 0 ? View.VISIBLE : View.GONE);
                } else {
                    adapter.setNewData(null);
                    Toasty.normal(activity, selectAllBean.getMsg()).show();
                }
                break;
            case 修改店铺商品信息:
                PubStatusBean pubStatusBean = (PubStatusBean) bindingViewBean.getBean();
                if ("0000000".equals(pubStatusBean.getCode())) {
                    getStoreList();
                }
                Toasty.normal(activity, pubStatusBean.getMsg()).show();

                break;
        }
    }


    @OnClick({R.id.ll_back, R.id.ll_right, R.id.tv_type1, R.id.tv_type2,
            R.id.tv_search, R.id.ll_search_result, R.id.fab_main})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.ll_right:
                Intent intent = new Intent(activity, StoreDetailsActivity.class);
                intent.putExtra("data", data);
                startActivity(intent);
                break;
            case R.id.tv_type1:

                showPop(type1Adapter);

                break;
            case R.id.tv_type2:

                showPop(type2Adapter);

                break;
            case R.id.tv_search:

                Toasty.normal(activity, "筛选！").show();

                break;
            case R.id.ll_search_result:
                startActivity(new Intent(activity, NotShelfGoodsActivity.class)
                        .putExtra("id", data.getId())
                        .putExtra("type1", type1Adapter.getData().get(type1Adapter.getCheckItemPosition()).getId())
                        .putExtra("type2", type2Adapter.getData().get(type2Adapter.getCheckItemPosition()).getId())
                        .putExtra("name1", type1Adapter.getData().get(type1Adapter.getCheckItemPosition()).getTypeName())
                        .putExtra("name2", type2Adapter.getData().get(type2Adapter.getCheckItemPosition()).getTypeName())
                );
                break;
            case R.id.fab_main:
                //TODO 新增
                startActivity(new Intent(activity, AddStoreActivity.class).putExtra("id", data.getId()));
                break;
        }
    }

    /**
     * 初始化adapter
     */
    void initAdapter() {
        type1Adapter = new ScreenAdapter(null);
        type2Adapter = new ScreenAdapter(null);

        type1Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                type1Adapter.setCheckItem(type1Adapter.getCheckItemPosition() == position ? -1 : position);
                if (type1Adapter.getCheckItemPosition() != -1)
                    businessDao.selectByLevel(2, type1Adapter.getData().get(position).getId());
                tvType1.setText(type1Adapter.getCheckItemPosition() == -1 ?
                        "请选择分类" : type1Adapter.getData().get(position).getTypeName());
                tvType2.setVisibility(type1Adapter.getCheckItemPosition() == -1 ? View.INVISIBLE : View.VISIBLE);
                popupWindow.dismiss();
            }
        });

        type2Adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                type2Adapter.setCheckItem(type2Adapter.getCheckItemPosition() == position ? -1 : position);
                tvType2.setText(type2Adapter.getCheckItemPosition() == -1 ?
                        "请选择服务组" : type2Adapter.getData().get(position).getTypeName());
                getStoreList();
                popupWindow.dismiss();
            }
        });

        adapter = new StoreManagementAdapter(null);
        vpMain.setLongPressDragEnabled(true);
        vpMain.setLayoutManager(new LinearLayoutManager(activity));


        vpMain.setOnItemMoveListener(new OnItemMoveListener() {
            @Override
            public boolean onItemMove(RecyclerView.ViewHolder srcHolder, RecyclerView.ViewHolder targetHolder) {
                // 此方法在Item拖拽交换位置时被调用。
                // 第一个参数是要交换为之的Item，第二个是目标位置的Item。
                // 交换数据，并更新adapter。
                int fromPosition = srcHolder.getAdapterPosition();
                int toPosition = targetHolder.getAdapterPosition();
                Collections.swap(adapter.getData(), fromPosition, toPosition);
                adapter.notifyItemMoved(fromPosition, toPosition);

                // 返回true，表示数据交换成功，ItemView可以交换位置。
                return true;
            }

            @Override
            public void onItemDismiss(RecyclerView.ViewHolder srcHolder) {
                // 此方法在Item在侧滑删除时被调用。

                // 从数据源移除该Item对应的数据，并刷新Adapter。
                int position = srcHolder.getAdapterPosition();
                adapter.getData().remove(position);
                adapter.notifyItemRemoved(position);
            }
        });// 监听拖拽，更新UI。

        SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int position) {

                SwipeMenuItem deleteItem1 = new SwipeMenuItem(activity)
                        .setBackgroundColor(getResources().getColor(R.color.red))
                        .setText("下架").setTextSize(13)
                        .setHeight(Tools.dip2Px(activity, 75))
                        .setWidth(Tools.dip2Px(activity, 50))
                        .setTextColor(getResources().getColor(R.color.white));
                rightMenu.addMenuItem(deleteItem1);
                // 注意：哪边不想要菜单，那么不要添加即可。
            }
        };

        vpMain.setSwipeMenuCreator(mSwipeMenuCreator);

        // 设置监听器。
        // 菜单点击监听。
        OnItemMenuClickListener mItemMenuClickListener = new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, final int position) {
                // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
                menuBridge.closeMenu();

                // 左侧还是右侧菜单：
                int direction = menuBridge.getDirection();
                if (direction == -1) {
                    // 菜单在Item中的Position：
                    switch (menuBridge.getPosition()) {
                        case 0:
                            Tools.showNormalDialogOne(activity, "下架", "是否将该商品下架"
                                    , new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            businessDao.ApiShopServiceUpdate(adapter.getData().get(position).getId(), 2);
                                        }
                                    }, null);
                            break;
                    }

                }

            }
        };
        vpMain.setOnItemMenuClickListener(mItemMenuClickListener);
        vpMain.setAdapter(adapter);
        adapter.setEmptyView(R.layout.rv_empty, vpMain);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(activity, AddStoreActivity.class);
                intent.putExtra("id", data.getId());
                intent.putExtra("name1", type1Adapter.getData().get(type1Adapter.getCheckItemPosition()).getTypeName());
                intent.putExtra("name2", type2Adapter.getData().get(type2Adapter.getCheckItemPosition()).getTypeName());
                intent.putExtra("data", StoreManagementActivity.this.adapter.getData().get(position));
                startActivity(intent);
            }
        });
    }


    private PopupWindow popupWindow;
    private View popupView;
    private TranslateAnimation animation;

    private void showPop(RecyclerView.Adapter adapter) {
        popupView = View.inflate(activity, R.layout.pop_screen, null);
        popupWindow = new PopupWindow(popupView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, true);

        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);


        animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, -1, Animation.RELATIVE_TO_PARENT, 0);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setDuration(200);


        RecyclerView rvScreen = popupView.findViewById(R.id.rv_screen);
        rvScreen.setLayoutManager(new LinearLayoutManager(activity));
        rvScreen.setHasFixedSize(true);
        rvScreen.setAdapter(adapter);
        rvScreen.addItemDecoration(new DividerItemDecoration(activity, DividerItemDecoration.HORIZONTAL));

        popupWindow.showAsDropDown(llTab);
        popupView.startAnimation(animation);

    }

    String[] shopStates = {"营业中", "歇业中", "已关闭"};

    /**
     * 设置界面中店铺信息
     */
    private void setViewData(SelectByIdBean.DataBeanX.DataBean bean) {
        data = bean;
        if (bean.getShopImage().length > 0)
            Picasso.get().load(!bean.getShopImage()[0].equals("") ? bean.getShopImage()[0] : "1")
                    .resize(1920, 1080)
                    .centerCrop()
                    .onlyScaleDown()
                    .into(imgPhoto);
        tvTitleName.setText(bean.getShopName());
        tvAddress.setText(bean.getAddress().replace(",", " "));
        if (bean.getShopState() != 0)
            tvIsBusiness.setText(shopStates[bean.getShopState() - 1]);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void Event(EventBusMsgBean e) {
        switch (e.getmEnumStatus()) {
            case 店铺信息修改:
                businessDao.selectAll(MainBActivity.User.getUserId());
                break;
        }
    }

    void getStoreList() {

//        if (type1Adapter.getCheckItemPosition() == -1 || type2Adapter.getCheckItemPosition() == -1) {
//            Toasty.normal(activity, "请先选择分类后再查询");
//            return;
//        }

        businessDao.ApiShopServiceSelectAll(data.getId(),
                type1Adapter.getData().get(type1Adapter.getCheckItemPosition()).getId(),
                type2Adapter.getData().get(type2Adapter.getCheckItemPosition()).getId(),
                1);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (type1Adapter.getCheckItemPosition() != -1 && type2Adapter.getCheckItemPosition() != -1)
            getStoreList();
    }
}
